<template>
  <div class="amap-page-container">
    <div style="position:absolute;top:100px;z-index:9999999;left:28%;width:50%">
      <mu-slider
        class="demo-slider"
        color="secondary"
        v-model="data_radius"
        :step="10"
        :max="20000"
      ></mu-slider>
    </div>
    <mu-appbar style="width: 100%;" color="#546e7a">
      <mu-menu slot="left">
        <mu-button icon @click="openTools" large style="top:0.3rem">
          <mu-icon value="explore"></mu-icon>
        </mu-button>
        <h2 style="display:inline-block;">
          【车辆检索】 当前中心坐标：{{ center[0] }} |
          {{ center[1] }} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;半径：{{
            circles[0].radius
          }}米
        </h2>
      </mu-menu>
      <mu-menu slot="right">
        <mu-auto-complete
          :data="search_dd"
          label="请输入你要查询的地点"
          :max-search-results="5"
          v-model="value_search"
          open-on-focus
          icon="search"
          underline-color="yellow"
          color="white"
        >
        </mu-auto-complete>
        <mu-button
          color="primary"
          style="margin-left:2rem;bottom:0.5rem"
          @click="search"
          >查询</mu-button
        >
      </mu-menu>
    </mu-appbar>
    <div
      :style="{ width: '100%', height: ' 96vh', position: 'relative' }"
      v-if="showmap"
    >
      <el-amap
        vid="amap"
        :plugin="plugin"
        class="amap-demo"
        :center="center"
        mapStyle="fresh"
        :events="events"
        :map-manager="amapManager"
      >
        <el-amap-marker
          vid="component-marker"
          :position="marker.position"
        ></el-amap-marker>
        <el-amap-circle
          v-for="circle in circles"
          :center="circle.center"
          :radius="circle.radius"
          :fill-opacity="circle.fillOpacity"
          :events="circle.events"
          :key="circle.radius"
        >
        </el-amap-circle>
        <el-amap-marker
          v-for="(v, k) in cm"
          :key="k"
          vid="component-marker"
          :position="v.position"
        ></el-amap-marker>
      </el-amap>
    </div>
    <tools
      :openAlert="showTools"
      @close="closeTools"
      :jd="center[0]"
      :wd="center[1]"
      :fw="circles[0].radius"
    ></tools>
    <mu-snackbar color="info" :open.sync="info_open" osition="bottom">
      <mu-icon left value="info"></mu-icon>
      {{ info_message }}
      <mu-button flat slot="action" color="#fff" @click="info_open = false"
        >Close</mu-button
      >
    </mu-snackbar>
    <mu-chip
      class="demo-chip"
      color="blue300"
      style="position:fixed;top:5rem;left:2%"
    >
      <mu-avatar text-color="blue300" color="indigo900" :size="32">@</mu-avatar>
      朱珺阳｜崔文博｜刘泽宇
    </mu-chip>
    <mu-chip
      class="demo-chip"
      color="blue300"
      style="position:fixed;top:8rem;left:2%"
    >
      <mu-avatar text-color="blue300" color="indigo900" :size="32">&</mu-avatar>
      指导老师：李莉
    </mu-chip>
    <mu-tooltip content="gitee仓库" placement="left-start">
      <mu-button
        fab
        color="info"
        style="position:fixed;bottom:15rem;left:95%"
        @click="jumpto"
      >
        <mu-icon value="thumb_up"></mu-icon>
      </mu-button>
    </mu-tooltip>
    <mu-tooltip content="GeoHash算法" placement="left-start">
      <mu-button
        fab
        color="info"
        style="position:fixed;bottom:5rem;left:95%"
        @click="openInfo"
      >
        <mu-icon value="report"></mu-icon>
      </mu-button>
    </mu-tooltip>
    <mu-tooltip content="车辆数据检索" placement="left-start">
      <mu-button
        fab
        color="info"
        style="position:fixed;bottom:10rem;left:95%"
        @click="openTools"
      >
        <mu-icon value="create"></mu-icon>
      </mu-button>
    </mu-tooltip>

    <mu-expansion-panel
      style="position:fixed;top:12rem;left:2%"
      class="panel"
      :expand="expand"
    >
      <div slot="header">车辆信息查询</div>
      <div>
        <p>
          中心经度：<strong>{{ center[1] }}</strong>
        </p>
        <p>
          中心纬度：<strong>{{ center[0] }}</strong>
        </p>
        <p>
          范围：<strong>{{ circles[0].radius }}</strong> 米
        </p>
        <p>
          geohash精度：<strong>{{ geohash_num }}</strong>
        </p>
        <li color="black"><strong>请选择时间</strong></li>
        <mu-date-input
          icon="today"
          v-model="time_data"
          label="选择年月"
          container="dialog"
          label-float
          full-width
        ></mu-date-input>
        <mu-date-input
          icon="today"
          landscape
          v-model="time1"
          label="选择开始时间"
          type="time"
          label-float
          full-width
        ></mu-date-input>
        <mu-date-input
          icon="today"
          landscape
          v-model="time2"
          label="选择结束时间"
          type="time"
          label-float
          full-width
        ></mu-date-input>
        <mu-alert
          color="info"
          @delete="alert1 = false"
          delete
          v-if="alert1"
          transition="mu-scale-transition"
          style="z-index:99999999"
        >
          <mu-icon left value="warning"></mu-icon>
          车辆信息请点击地图内的圆圈查看哦
        </mu-alert>
      </div>
      <mu-button slot="action" flat color="primary" @click="confirm_info"
        >确认</mu-button
      >
    </mu-expansion-panel>
    <info @close="closeInfo" :openInfo="showInfo"></info>
    <info2
      ref="info2"
      v-if="hasdata"
      @close="closeInfo2"
      :list="listData"
      @change-marker="changeMarker"
    ></info2>
    <!-- -->
  </div>
</template>
<style>
.amap-demo {
  height: 100%;
}
.panel {
  opacity: 0.9;
}
.mu-scale-transition-enter-active,
.mu-scale-transition-leave-active {
  transition: transform 0.45s cubic-bezier(0.23, 1, 0.32, 1),
    opacity 0.45s cubic-bezier(0.23, 1, 0.32, 1);
  backface-visibility: hidden;
}

.mu-scale-transition-enter,
.mu-scale-transition-leave-active {
  transform: scale(0);
  opacity: 0;
}
</style>

<script>
import tools from '@/components/tools'
import info from '@/components/info'
import info2 from '@/components/informations'
import config from '@/common/config'
import { AMapManager } from 'vue-amap'
let amapManager = new AMapManager()
export default {
  components: {
    tools,
    info,
    info2
  },
  data() {
    const self = this
    return {
      amapManager,
      showmap: true,
      center: [118.11827663845497, 24.496937934028],
      lng: 0,
      lat: 0,
      listData: [],
      gpsPath: [],
      alert1: false,
      search_dd: [],
      loaded: false,
      value_search: '',
      info_message: '',
      info_open: false,
      timer: null,
      showInfo2: false,
      marker: {
        position: []
      },
      activeStep: 0,
      time_data: '2019-06-07',
      time1: null,
      time2: null,
      expand: true,
      showInfo: false,
      data_radius: null,
      showTools: false,
      plugin: [
        {
          pName: 'MapType',
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 100, //超过10秒后停止定位，默认：无穷大
          maximumAge: 0, //定位结果缓存0毫秒，默认：0
          convert: false, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
          extensions: 'all',
          pitch: 75, // 地图俯仰角度，有效范围 0 度- 83 度
          viewMode: '3D', // 地图模式
          zoom: 10
          //pName: 'Geolocation',
        }
      ],

      events: {
        click: (e) => {
          self.center = []
          self.circles[0].center = []
          self.marker.position = []
          const lng = e.lnglat.lng
          const lat = e.lnglat.lat
          self.center[0] = lng
          self.center[1] = lat
          self.circles[0].center[0] = lng
          self.circles[0].center[1] = lat
          self.marker.position[0] = lng
          self.marker.position[1] = lat
          self.$set(self.circles[0].center, 0, lng)
          self.$set(self.circles[0].center, 1, lat)
          self.$set(self.marker.position, 0, lng)
          self.$set(self.marker.position, 1, lat)
          console.log(self.circles)
        },
        init(map) {
          AMapUI.loadUI(['misc/PathSimplifier'], function(PathSimplifier) {
            const marker = new PathSimplifier({
              zIndex: 100,
              //autoSetFitView:false,
              map: map, //所属的地图实例

              getPath: function(pathData) {
                return pathData.path
              },
              getHoverTitle: function(pathData, pathIndex, pointIndex) {
                if (pointIndex >= 0) {
                  //point
                  return (
                    pathData.name +
                    '，点：' +
                    pointIndex +
                    '/' +
                    pathData.path.length
                  )
                }

                return pathData.name + '，点数量' + pathData.path.length
              },
              renderOptions: {
                pathNavigatorStyle: {
                  initRotateDegree: 0,
                  renderAllPointsIfNumberBelow: -1,
                  width: 24,
                  height: 24,
                  autoRotate: true,
                  lineJoin: 'round',
                  content: 'defaultPathNavigator',
                  fillStyle: '#087EC4',
                  strokeStyle: '#116394', //'#eeeeee',
                  lineWidth: 4,
                  pathLinePassedStyle: {
                    lineWidth: 6,
                    strokeStyle: 'rgba(8, 126, 196, 1)',
                    borderWidth: 1,
                    borderStyle: '#eeeeee',
                    dirArrowStyle: {
                      stepSpace: 15,
                      strokeStyle: 'red'
                    }
                  }
                }
              }
            })

            window.pathSimplifierIns = marker

            //设置数据
            marker.setData([
              {
                name: '路线0',
                path: self.gpsPath
              }
            ])

            //对第一条线路（即索引 0）创建一个巡航器
            var navg1 = marker.createPathNavigator(0, {
              loop: true, //循环播放
              speed: 4000 //巡航速度，单位千米/小时
            })

            navg1.start()
          })
        }
      },
      circles: [
        {
          center: [],
          radius: 50,
          fillOpacity: 0.5,
          fillColor: '#1E90FF',
          strokeColor: '#1E90FF',
          events: {
            click: () => {
              //alert('click');
              self.hasdata = true
              console.log(this.$refs)
            }
          }
        }
      ],
      cm: [],
      geohash: '',
      geohash_num: 7,
      hasdata: false
    }
  },
  methods: {
    getinfo(e) {
      console.log(e)
    },
    openTools() {
      this.showTools = true
    },
    closeTools() {
      this.showTools = false
    },
    reload() {
      this.showmap = false
      this.$nextTick(() => {
        this.showmap = true
      })
    },
    search() {
      var that = this
      if (this.value_search != '') {
        this.$axios({
          methods: 'GET',
          url:
            'https://restapi.amap.com/v3/config/district?keywords=' +
            this.value_search +
            '&subdistrict=0&key=7c9113e5d8fd4fe2153551b9787dd82c'
        }).then(function(res) {
          console.log(res.data)
          if (res.data.count != '0') {
            let data = res.data.districts[0].center.split(',')
            console.log(data)
            that.center = data
            that.$set(that.center, 0, data[0])
            that.$set(that.center, 1, data[1])
            that.circles[0].center = data
            that.$set(that.circles[0].center, 0, data[0])
            that.$set(that.circles[0].center, 1, data[1])
            that.marker.position = data
            that.$set(that.marker.position, 0, data[0])
            that.$set(that.marker.position, 1, data[1])
            that.info_open = true
            that.info_message = '查询到信息：' + res.data.districts[0].name
            if (that.timer) clearTimeout(that.timer)
            that.time = setTimeout(() => {
              that.info_open = false
            }, 0)
          } else {
            that.info_open = true
            that.info_message = '没有查询到相关行政区域信息！'
            if (that.timer) clearTimeout(that.timer)
            that.time = setTimeout(() => {
              that.info_open = false
            }, 3000)
          }
        })
      } else {
        this.info_open = true
        this.info_message = '请检查输入内容！'
        if (this.timer) clearTimeout(this.timer)
        this.time = setTimeout(() => {
          this.info_open = false
        }, 3000)
      }
    },
    openInfo() {
      this.showInfo = true
    },
    closeInfo() {
      this.showInfo = false
    },
    closeInfo2() {
      this.hasdata = false
    },
    jumpto() {
      window.open('https://gitee.com/zhu-junyang_admin/database-competition')
    },
    confirm_info() {
      let that = this
      if (this.activeStep != 1) {
        this.activeStep++
        this.alert1 = true
      }
      const startTime =
        this.dateFtt('yyyy-MM-dd', this.time_data) +
        ' ' +
        this.dateFtt('hh:mm:ss', this.time1)
      const endTime =
        this.dateFtt('yyyy-MM-dd', this.time_data) +
        ' ' +
        this.dateFtt('hh:mm:ss', this.time2)
      this.$axios({
        method: 'post',
        url: this.$config.goapi + 'geohash',
        data: this.$qs.stringify({
          lng: this.center[0],
          lat: this.center[1]
        })
      }).then(function(res) {
        console.log(res)
        console.log(that.geohash_num)
        const num_str = res.data.data.substring(0, that.geohash_num)
        that.cm = []
        that.listData = []
        that
          .$axios({
            method: 'post',
            url: that.$config.goapi + 'search',
            data: that.$qs.stringify({
              geohash: num_str,
              start: startTime,
              end: endTime
            })
          })
          .then(function(res) {
            const length = res.data.data.length
            const data = res.data.data
            for (let i = 0; i < length; i++) {
              that.$forceUpdate()
              let info = []
              info.push(data[i].Lng)
              info.push(data[i].Lat)
              that.cm[i] = { position: info }
              that.listData[i] = {
                carno: data[i].Carno,
                direction: data[i].Direction,
                speed: data[i].Speed,
                time: data[i].Time,
                lng: data[i].Lng,
                lat: data[i].Lat
              }
            }
            console.log(that.listData)
            console.log(that.cm)
          })
      })
    },
    // 轨迹绘制
    changeMarker(data) {
      const that = this
      that.gpsPath = []
      that.hasdata = false
      for (let i = 0; i < data.length; i++) {
        that.$forceUpdate()
        let info = []
        info.push(data[i].Lng)
        info.push(data[i].Lat)
        this.gpsPath.push(info)
      }
      alert('转换完成！')
      that.reload()
    },
    dateFtt(fmt, date) {
      var o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        S: date.getMilliseconds()
      }
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      for (var k in o)
        if (new RegExp('(' + k + ')').test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length)
          )
      return fmt
    }
  },
  watch: {
    data_radius: function(e) {
      this.circles[0].radius = e
      if (e <= 20000 && e >= 2400) {
        this.geohash_num = 6
      } else if (e < 2400 && e >= 610) {
        this.geohash_num = 6
      } else if (e < 610 && e >= 150) {
        this.geohash_num = 7
      } else {
        this.geohash_num = 8
      }
      console.log(this.geohash_num)
    },
    value_search: function(e) {
      let that = this
      this.$axios({
        methods: 'GET',
        url:
          'https://restapi.amap.com/v3/assistant/inputtips?keywords=' +
          e +
          '&key=7c9113e5d8fd4fe2153551b9787dd82c'
      }).then(function(res) {
        console.log(res)
        const tips = res.data.tips
        that.search_dd = []
        for (let i = 0; i < tips.length; i++) {
          that.search_dd.push(tips[i].name)
          that.$set(that.search_dd, i, tips[i].name)
        }
      })
    }
  },
  mounted() {
    this.circles[0].center = []
    this.circles[0].center.push(this.center[0])
    this.circles[0].center.push(this.center[1])
    this.marker.position.push(this.circles[0].center[0])
    this.marker.position.push(this.circles[0].center[1])
    this.data_radius = this.circles[0].radius
  }
}
</script>
